package project.server.game;

import java.util.ArrayList;
import java.util.Iterator;

import project.server.handlers.Client;
import project.server.handlers.OutboundMessages;
import project.server.util.Logger;
import project.shared.messages.StartMessage;
import project.shared.player.Player;
import project.shared.util.Config;
import project.server.game.GameHandler;

public class GameStarter extends Thread {
	private ArrayList<Client> inGame = new ArrayList<Client>();
	private OutboundMessages outQueue;
	private int gameId;
	private int playerCount = 1;
	private Player p1, p2, p3;
	private Logger logger;
	private Config config;
	
	public GameStarter(ArrayList<Client> newGame, OutboundMessages out, int gameId, Logger logger, Config config){
		inGame.addAll(newGame);
		this.outQueue = out;
		this.gameId = gameId;
		this.logger = logger;
		this.config = config;
		start();
	}
	
	public void run(){
		Iterator<Client> itr = inGame.iterator();
		while(itr.hasNext()){
			Client cli = itr.next();
			switch(playerCount){
			case 1:
				p1 = cli.p = new Player(cli.getName(), gameId, playerCount);
				break;
			case 2:
				p2 = cli.p = new Player(cli.getName(), gameId, playerCount);
				break;
			case 3:
				p3 = cli.p = new Player(cli.getName(), gameId, playerCount);
			}
			playerCount++;
			if(playerCount == 4){
				outQueue.addMessage(new StartMessage(gameId, p1, p2, p3));
				break;
			}
		}
		while(true){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				logger.logError("GameStart - run() - sleep interrupted.");
			}
			if(checkReady()){
				logger.log("Game " + gameId + " started.");
//				new GameController(outQueue, gameId, p1, p2, p3, logger, config);
				break;
			}
		}
	}
	
	private boolean checkReady() {
		Iterator<Client> itr = inGame.iterator();
		while (itr.hasNext()) {
			Client cli = itr.next();
			if (!cli.getReady()) {
				return false;
			}
		}
		return true;
	}
}
